package com.qf.controller;

import com.qf.aop.annocation.LoginToken;
import com.qf.entity.*;
import com.qf.feign.api.IAddressService;
import com.qf.feign.api.ICarMySQLService;
import com.qf.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IAddressService addressService;

    @Autowired
    private ICarMySQLService carMySQLService;

    @Autowired
    private IOrderService orderService;

    @RequestMapping("/toOrderConfrim")
    @LoginToken
    public String toOrderConfrim(User user, Model model) {

        // 1.先根据用户id查询地址信息
        List<Address> addressList = addressService.getAddressListByUid(user.getId());

        // 2.用户的购物车
        Map<String, Object> map = carMySQLService.getCarListByUserId(user.getId());

        Object carList = map.get("carList");
        Object totalPrice = map.get("totalPrice");

        // 3.
        model.addAttribute("carList", carList);
        model.addAttribute("addressList", addressList);
        model.addAttribute("totalPrice", totalPrice);
        System.out.println(map);

        return "orderConfrim";
    }

    @RequestMapping("/addOrder")
    @LoginToken
    // @ResponseBody
    public String addOrder(User user, Integer addressId) throws Exception{

        // 1.添加订单
        String orderId = orderService.addOrder(user.getId(), addressId);

        System.out.println("orderId:"+orderId);
        System.out.println("userId:"+user.getId());
        // 2.跳转到支付平台
//        return "redirect:http://localhost/shop-pay/pay/alipay?orderId="+orderId+"&userId="+user.getId();
        return "redirect:http://localhost:8093/pay/alipay?orderId="+orderId+"&userId="+user.getId();
    }

    @RequestMapping("/getOrderById/{uid}/{orderId}")
    @ResponseBody
    public Order getOrderById(@PathVariable Integer uid,@PathVariable String orderId){
        Order order = orderService.getOrderById(uid,orderId);
        return order;
    }

    @RequestMapping("/updateOrderStatus")
    @ResponseBody
    public void updateOrderStatus(String orderId,String status){
        orderService.updateOrderStatus(orderId,status);
    }

    @RequestMapping("/getOrderListByUid")
    @LoginToken
    public String getOrderListByUid(User user,Model model){
        List<Order> orderList =orderService.getOrderListByUid(user.getId());
        model.addAttribute("orderList",orderList);
        return "orderList";
    }
}
